<template>
	<div class="index">
		<div class="index_title">
			<Titles titles="常用模板"></Titles>
			<div class="selects">
			  <el-select v-model="value" multiple collapse-tags placeholder="请选择" @change="changeSelect">
			    <el-option
			      v-for="item in options"
			      :key="item.value"
			      :label="item.label"
			      :value="item.value">
			    </el-option>
			  </el-select>
			</div>
		</div>

		<div class="index_content">
			<div ref="QRcodeSrcImg" :style="typeWidth">
		            <grid-layout
	                    :layout.sync="layout"
	                    :col-num="parseInt(colNum)"
	                    :row-height="rowHeight"
	                    :min-rows = "minRows"
	                    :is-draggable="draggable"
	                    :is-resizable="resizable"
	                    :is-mirrored="mirrored"
	                    :prevent-collision="preventCollision"
	                    :vertical-compact="false"
	                    :use-css-transforms="false"
	                    :responsive="responsive"

	                    @layout-created="layoutCreatedEvent"
	                    @layout-before-mount="layoutBeforeMountEvent"
	                    @layout-mounted="layoutMountedEvent"
	                    @layout-ready="layoutReadyEvent"
	                    @layout-updated="layoutUpdatedEvent"
	            >
	                <grid-item v-for="(item,index) in layout" :key="item.i"
	                           :static="item.static"
	                           :x="item.x"
	                           :y="item.y"
	                           :w="item.w"
	                           :h="item.h"
	                           :i="item.i"
	                           @resize="resize"
	                           @move="move"
	                           @resized="resized"
	                           @moved="moved"
	                >
	                	<i class="el-icon-delete" @click="deletes(item,index)"></i>
	                    <!--<custom-drag-element :text="item.i"></custom-drag-element>-->
	                    <!-- <test-element :text="item.i"></test-element> -->
	                    {{item.i}}
	                    <!-- <img :src="item.img+'?'+new Date().getTime()" alt="" crossOrigin="anonymous"> -->
	                    <!--<button @click="clicked">CLICK ME!</button>-->
	                </grid-item>
	            </grid-layout>
            </div>

		</div>
	</div>
</template>
<script>
	import Titles from '@/components/title.vue'
	import VueGridLayout from 'vue-grid-layout'
	export default{
		components:{
			Titles,
			GridLayout: VueGridLayout.GridLayout,
            GridItem: VueGridLayout.GridItem
		},
		data(){
			return{
		        options: [{
		          value: '1',
		          label: '黄金糕',

		        }, {
		          value: '2',
		          label: '双皮奶'
		        }, {
		          value: '3',
		          label: '蚵仔煎'
		        }, {
		          value: '4',
		          label: '龙须面'
		        }, {
		          value: '5',
		          label: '北京烤鸭'
		        }],
		        value: [],

    			tabsindex:0,
    			subgroups:[],
    			subgroup:[],
    			layout:[],
    			componentsid:'',
    			componentName:'',
                // layout: [],
                draggable: true,
                resizable: true,
                mirrored: false,
                responsive: false,
                // responsive: false,
                preventCollision: true,
                rowHeight: 150,
                colNum: 3,
                index: 0,
                minRows:12,
                address:[],
                src_img:'',
                client:null,
                menu:[],
                typeWidth:'',
                loading:null,   //加载事件
                saveType:0,     //0 保留班级 1不保留班级
                state:null,     //判断是否有班级使用当前模板
                type:0,          //  1/横屏  2/竖屏
                maxNum:0,		//
                add:false 		//判断是否有另存
			}
		},
		created(){
			if(!!localStorage.val){
				this.value = JSON.parse(localStorage.val)
			}
		},
		watch:{
			value(newVal,oldVal){
				console.log(newVal,oldVal)
				if(newVal.length - oldVal.length >0){
			 		let arr = this.getArrDifference(newVal,oldVal);
			 		this.layout = []
			 		this.options.forEach((item,index)=>{
			 			arr.forEach((items,indexs)=>{
			 				if(item.value == items){
			 					this.addItem(item);
			 				}
			 			})

			 		})
			 	}
			 	else{
			 		let arr = this.getArrDifference(newVal,oldVal);
			 		this.layout.forEach((item,index)=>{

			 			if(item.id == arr[0]){
			 				this.layout.splice(index,1)
			 			}
			 		})
			 	}
				// this.addItem(newVal,);
			}
		},
		methods:{
			// 去重 获取到不相同的数据
			getArrDifference(arr1,arr2){
				return arr1.concat(arr2).filter((v,i,arr)=>{
					return arr.indexOf(v) === arr.lastIndexOf(v)
				})
			},
			changeSelect(e){
				this.value = e;
				localStorage.val = JSON.stringify(this.value)
				console.log(e)
			},
			clearComponents(e){
    			this.layout.forEach((item,index)=>{
    				this.subgroups.push({id:item.id,img:item.img,zname:item.i})
    				this.address.push({x:item.x,y:item.y})
    			})
    			this.layout = [];

    		},
			getcomponent(e) {
				this.$axios.post(this.apiUrl+'/media/queryMenuComponent.do').then(res=>{
					if(res.data.code=="5000"){
						this.subgroups = res.data.data;
					}
				})
			},
			// 查询编辑跳转过来的模板组件
			queryTemplates(e){
				let data={
					templateid:e
				};
				this.$axios.get(this.apiUrl + "/media/queryMenuTemplate.do",{params:data}).then(res=>{
					if(res.data.code=="5000"){
						res.data.data.forEach((item,index)=>{
							this.subgroups.forEach((items,indexs)=>{
								if(items.id == item.id){
									this.subgroups.splice(indexs,1)
								}
							})
							this.layout.push({x:Number(item.x),y:Number(item.y),w:Number(item.xnum),h:Number(item.ynum),id:item.id,i:item.zname,img:item.img})
						})
						this.componentName = res.data.data[0].name;
					}
				})
			},
			// base64转换成blob
			dataURLtoBlob(dataurl) {
			    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
			        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
			    while (n--) {
			        u8arr[n] = bstr.charCodeAt(n);
			    }
			    var ext = dataurl.split(';')[0].split(':')[1].split('/')[1];
			    // var file_name = `${new Date().getTime()}.${ext}`
			    return this.blobToFile(new Blob([u8arr], { type: mime }));
			},
			//将blob转换为file
			blobToFile(theBlob) {
				theBlob.lastModifiedDate = new Date();
				theBlob.name = theBlob.lastModifiedDate.getTime()+'.'+theBlob.type.split("/")[1];
				theBlob.lastModified = theBlob.lastModifiedDate.getTime();
				return new File([theBlob],theBlob.name);
			},
			getaddress(){
				let address=[];
				for(var j=0;j<this.minRows;j++){
					for(var i=0;i<this.colNum;i++){
						address.push({x:i,y:j})
					}
				}
				this.address = address;
				return address;
			},
			uploadImage(file){

				console.log(file)
				let file_name = file.name;
				//let ext = file.type.split("/")[1];
				// var type = file.name.match(/\.(\w+)$/)[1]; //获取上传文件后缀名
		        //var storeAs = "upload-file1/abc";
		        //var file_name = `${new Date().getTime()}.${ext}`; //时间戳+文件后缀名
		        this.client = new OSS.Wrapper({
		          region: "oss-cn-shenzhen",
		          secure: true,
		          //endpoint: "oss-cn-shenzhen.aliyuncs.com",
		          accessKeyId: "TxkBX1VgU792UUVh",
		          accessKeySecret: "45sBqHvJR7YeHj8qL5h0tsmvYdiA0W",
		          bucket: "mixin"
		        });
		        this.client.multipartUpload('zujianmoban/'+file_name, file).then(result => {
		            if (result.res.status == 200 && result.res.statusCode == 200) {
		              // this.$message.success("上传成功");
		              this.src_img = result.res.requestUrls[0].split("?")[0];

	      				let data={
	      					templateid:!!this.templateid?this.templateid:"",
							url:this.src_img,
							name:this.componentName,
							menuclass:this.menu,
						};
						if(this.saveType == 1){
							data.templateid = ""
						}
		              	this.formDatas(data);
		              // return result.res.requestUrls[0].split("?")[0];

		            } else {
		              this.$message.error("上传失败，请重新上传文件");
		            }
		          })
		          .catch(function (err) {
		        //    console.log(err);
		          });
		      },
      			// 另存模板
				another(){

  					if(this.componentName == ""){
						this.$message.error('请填写模板名称!');
						return false;
					}
					let count = 0;
					this.saveType = 1;
					this.menu = [];
					this.layout.forEach((item,index)=>{
						console.log("x:"+item.x,"y:"+item.y);
						count+=item.w*item.h;
						this.menu.push({menuid:item.id,x:item.x,y:item.y,xnum:item.w,ynum:item.h,type:this.type})
					})
					if(count<this.colNum*this.maxRows){
						this.$message.error('请添加完整模板!')
						return false;
					}
					for(let i=0;i<this.menu.length;i++){
						if(this.menu[i].y>this.maxRows-1){
							this.$message.error('请确认所有组件在画布内!');
							return false;
						}
					}

					this.Html2Canvas();
				},
		      // axios提交请求
		      formDatas(data){
				$.ajax({
					url: this.apiUrl + '/media/addMenuTemplate.do',
					type: 'post',
					headers: {
						Authorization: sessionStorage.getItem('Authorization')
					},
					contentType: "application/json",
					data:JSON.stringify(data),
					success: res => {
						console.log(res);
						if(res.code=="5000"){
							this.$message.success('保存成功!');
							this.loading.close();
							setTimeout(()=>{
								this.$router.go(-1);
							},1000);
						}
						else{
							this.$message.error(res.message);
							this.loading.close();
						}
					}
				})
		      },
		      // 提交模板
			submit(e) {
				if(this.componentName == ""){
					this.$message.error('请填写模板名称!');
					return false;
				}
				let count = 0;
				this.menu = [];
				this.layout.forEach((item,index)=>{
					console.log("x:"+item.x,"y:"+item.y);
					count+=item.w*item.h;
					this.menu.push({menuid:item.id,x:item.x,y:item.y,xnum:item.w,ynum:item.h,type:this.type})
				})
				if(count<this.colNum*this.maxRows){
					this.$message.error('请添加完整模板!')
					return false;
				}
				for(let i=0;i<this.menu.length;i++){
					if(this.menu[i].y>this.maxRows-1){
						this.$message.error('请确认所有组件在画布内!');
						return false;
					}
				}
				if(!!this.state){
					this.$confirm('是否保留已使用该模板的班级?','提示',{
						distinguishCancelAndClose:true,
						confirmButtonText:'保留',
						cancelButtonText:'取消'
					}).then(res=>{
						// this.saveType = 0;
						this.Html2Canvas();
					}).catch(()=>{
						// this.saveType = 1;
						// this.Html2Canvas();
					})	
				}
				else{
					this.Html2Canvas();
				}


			},
			// 截图
			Html2Canvas(){
				this.loading = this.$loading({
			        lock: true,
			        text: 'Loading',
			        spinner: 'el-icon-loading',
			        background: 'rgba(0, 0, 0, 0.7)'
				})
					//做一个等待加载的
                let that = this;
			      // let _this = this;
			      // _this.photoShow = true;
			      // 声明一个画布元素,存储需下载图片范围
			      let canvas = document.createElement("canvas");
			      // 获取需下载范围元素
			      let img = this.$refs["QRcodeSrcImg"];
			      // 图片高度
			      var w = parseInt(window.getComputedStyle(img).width);
			      // 图片宽度
			      var h = parseInt(window.getComputedStyle(img).height);
			      // 声明画布宽高
			      canvas.width = w*4;
			      canvas.height = h*4;
			      canvas.style.width = w + "px";
			      canvas.style.height = h + "px";
			      let context = canvas.getContext("2d");
			      context.scale(2, 2);
			      // 利用 html2canvas 下载 canvas
			      html2canvas(img, {
			          //canvas: canvas, //自定义 canvas
			          //logging: false, //日志开关，便于查看html2canvas的内部执行流程
			          useCORS: true // 【重要】开启跨域配置
			      }).then(function(canvas) {
		                var imgData=that.dataURLtoBlob(canvas.toDataURL('image/png'));
		                that.uploadImage(imgData)
			      });
			},
            // 切换横屏
            tabs(e){
                this.tabsindex = e;
            },
			clicked: function() {
                window.alert("CLICK!");
            },
            increaseWidth: function() {
                let width = document.getElementById("content").offsetWidth;
                width += 20;
                document.getElementById("content").style.width = width+"px";
            },
            decreaseWidth: function() {
                let width = document.getElementById("content").offsetWidth;
                width -= 20;
                document.getElementById("content").style.width = width+"px";
            },
            removeItem: function(item) {
                //console.log("### REMOVE " + item.i);
                this.layout.splice(this.layout.indexOf(item), 1);
            },
            recursion(json,data){
                for(let i=0;i<json.length;i++){
                    for(let j=0;j<data.length;j++){
                        if(json[i].x == data[j].x){
                            if(json[i].y == data[j].y){
                                data.splice(j,1);

                            }
                        }
                    }
                }
                return {x:data[0].x,y:data[0].y};
            },
			deletes(v,i){
				console.log("i:"+i);
				// this.$confirm('是否删除该组件?','提示',{
		  //           confirmButtonText: '确定',
		  //           cancelButtonText: '取消',
		  //           type: 'warning'
				// }).then(()=>{
					this.subgroups.splice(v.index,0,{zname:v.i,id:v.id,img:v.img});
					this.address.push({x:v.x,y:v.y});
					this.layout.splice(i,1);
					this.$message.success('删除成功!');
				// })

			},
            addItem: function(item) {
            	// console.log(item)
            	// console.log(index);
                // let self = this;
                //console.log("### LENGTH: " + this.layout.length);
                let address = this.getaddress();
                let colNum = 0 ;
                this.layout.forEach((items,indexs)=>{
                	colNum+=Number(items.w*items.h);
                })

                if(colNum>=this.colNum*this.maxRows){
                	this.maxNum++;
                	// console.log(maxNum)
                	if(this.maxNum>1){
                		return false;
                	}
                	this.$message.warning('已经超过最大范围!');
                	return false;
                }

                // let val = this.recursion(this.layout,this.address);
                this.address = this.deleteAddress(address);
                console.log(this.address)
                let items = {"x":this.address[0].x,"y":this.address[0].y,"w":1,"h":1,"i":item.label,id:item.value};
                console.log(items)
                this.layout.push(items);
                // this.index++;
                // this.address.splice(0,1);
                // this.subgroups.splice(index,1);
            },
            // 去除内置坐标
            deleteAddress(address){
            	if(this.layout.length == 0) return address;
            	this.layout.forEach((item,index)=>{

	            	let w = item.w,h = item.h,x = item.x,y=item.y,deladdress=[];
	            	// layout里面组件占有的坐标
	            	for(let i=x;i<x+w;i++){
	            		for(let j=y;j<y+h;j++){
	            			deladdress.push({x:i,y:j})
	            		}	
	            	}
	            	// 删除address库内组件占有的坐标
			 		let lenA = address.length;
			 		for(let i=lenA-1;i>=0;i--){
			 			for(let j=0;j<deladdress.length;j++){
			 				if(address[i]){
			 					if(address[i].x == deladdress[j].x&&address[i].y == deladdress[j].y){
			 						console.log(address);
			 						address.splice(i,1);
			 						continue
			 					}
			 				}
			 			}
			 		}
			 	})
		 		return address;
            },
            move: function(i, newX, newY){
                console.log("MOVE i=" + i + ", X=" + newX + ", Y=" + newY);
            },
            resize: function(i, newH, newW, newHPx, newWPx){
                console.log("RESIZE i=" + i + ", H=" + newH + ", W=" + newW + ", H(px)=" + newHPx + ", W(px)=" + newWPx);
            },
            moved: function(i, newX, newY){
                console.log("### MOVED i=" + i + ", X=" + newX + ", Y=" + newY);
            },
            resized: function(i, newH, newW, newHPx, newWPx){
                console.log("### RESIZED i=" + i + ", H=" + newH + ", W=" + newW + ", H(px)=" + newHPx + ", W(px)=" + newWPx);
            },
            /**
             * Add change direction button
             */
            changeDirection() {
                let documentDirection = getDocumentDir();
                let toggle = "";
                if (documentDirection === "rtl") {
                    toggle = "ltr"
                } else {
                    toggle = "rtl"
                }
                setDocumentDir(toggle);
                //eventBus.$emit('directionchange');
            },

            layoutCreatedEvent: function(newLayout){
                console.log("Created layout: ", newLayout)
            },
            layoutBeforeMountEvent: function(newLayout){
                console.log("beforeMount layout: ", newLayout)
            },
            layoutMountedEvent: function(newLayout){
                console.log("Mounted layout: ", newLayout)
            },
            layoutReadyEvent: function(newLayout){
                console.log("Ready layout: ", newLayout)
            },
            layoutUpdatedEvent: function(newLayout){
                console.log("Updated layout: ", newLayout)
            },
		}
	}
</script>
<style lang="scss" scoped>
	.index_title{
		display: flex;
		align-items: center;
		background: #fff;
		justify-content: space-between;
		padding-top:10px; 
		.selects{
			margin-right: 30px;
		}
	}

	.index{
		.index_content{
			.vue-grid-layout{
				.vue-grid-item{
					background: #fff;
					box-shadow: 0 0 10px #eee;
				}
			}
		}
	}
</style>